package cn.youth996.utils;

import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import com.volcengine.ark.runtime.service.ArkService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: quequnlong
 * @date: 2025/2/17
 * @description:
 */
@Component
@Slf4j
public class AiUtil {

    @Value("${ai.apiKey}")
    private String apiKey;

    @Value("${ai.baseUrl}")
    private String baseUrl;

    @Value("${ai.model}")
    private String model;

    private ArkService service = null;
    @Autowired
    private RedisUtil redisUtil;

    //这里可以初始化AI的角色
//    public final List<ChatMessage> messages = new ArrayList<>(Collections.singletonList(ChatMessage.builder()
//            .role(ChatMessageRole.SYSTEM).content("你是豆包，是由字节跳动开发的 AI 人工智能助手").build()));


    private void initService() {
        if (service == null) {
            synchronized (AiUtil.class) {
                if (service == null) {
                    service = ArkService.builder()
                            .apiKey(apiKey)
                            .timeout(Duration.ofMinutes(30))
                            .baseUrl(baseUrl)
                            .build();
                }
            }
        }
    }



    public String send(String content) {
        initService(); // 保证只初始化一次，线程安全
        List<ChatMessage> messages = new ArrayList<>();

        messages.add(ChatMessage.builder()
                .role(ChatMessageRole.USER)
                .content(content)
                .build());

        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model(model)
                .messages(messages)
                .build();

        List<Object> responses = new ArrayList<>();
        try {
            service.createChatCompletion(request).getChoices().forEach(choice -> {
                log.info("推理内容: " + choice.getMessage().getReasoningContent());
                log.info("消息内容: " + choice.getMessage().getContent());
                responses.add(choice.getMessage().getContent());
            });
        } catch (Exception e) {
            log.error("AI请求失败: " + e.getMessage(), e);
            // 返回友好的错误提示，而不是空字符串
            return "抱歉，我现在有点忙，请稍后再试~";
        }

        return responses.isEmpty() ? "抱歉，我没有理解您的问题，请换个方式提问~" : responses.get(0).toString();
    }
}
